<?php
namespace Wx\Controller;
use Think\Controller;
class AutofocusmsgController extends Controller {
	//用户id 、 产品标题 、 跳转url 保存在cache中
	public function setxcache($u_id=0,$title='',$url=''){
		//$u_id=3000;$title="烂鸡蛋";$url="http://www.xiangtws.com/index.php/Wx/Prodetail/index/id/495/";//dump("666");
		if($u_id==0)return 0;
		if($title=='')return 0;
		if($url=='')return 0;
		//dump(session('focus'));
		if(session('focus')==0){
			$cache=S(array(
				'type'=>'memcache',
				'host'=>'127.0.0.1',
				'port'=>'11211',
				'prefix'=>'focus',
				'expire'=>86400)
			);
			//用户id拼接为字符串
			$uidstr=$cache->uidstr;
			
			$uidstr=$uidstr.','.$u_id;//dump($uidstr);
			//处理多余的逗号		
			$uidstr=preg_replace('/(,)+/i',',',$uidstr);
			$uidstr=rtrim($uidstr,',');//去尾
			$uidstr=ltrim($uidstr,',');//去头
			$uidarr=explode(',',$uidstr);//dump($uidarr);//转换为数组
			$uidarr=array_unique($uidarr);//dump($uidarr);//数组去重
			$uidstr=implode(',',$uidarr);//dump($uidstr);//转换为字符串
			//用户id拼接为字符串 存储到缓存
			$cache->uidstr=$uidstr;
			//dump($uidstr);
			
			//信息存储到缓存
			$ca_title="title_".$u_id;
			$cache->$ca_title=$title;
			$ca_url="url_".$u_id;
			$cache->$ca_url=$url;
		}//end if
	}//end fun
	
	//遍历推送关注前查看的商品
	public function sendmsg(){
		//修改最大执行时间
		ini_set('max_execution_time', '60');
		$cache=S(array(
			'type'=>'memcache',
			'host'=>'127.0.0.1',
			'port'=>'11211',
			'prefix'=>'focus',
			'expire'=>86400)
		);
		$f_time=time();//开始执行的时间
		againrun:
		if(session('focusmsg')==1){		
			echo "有一个在推送则不再推送!	";
			goto sleeping;
			//return 0;
		}//end if
		session('focusmsg',1);  //"已经在推送消息"
		$uidstr=$cache->uidstr;
		$uidarr=explode(',',$uidstr);dump($uidstr);//转换为数组
		foreach($uidarr as $i=>$one){
			//dump($one);
			//检测是否关注
			$sc=new \Wx\Controller\AuthnoticeController();  //用绝对路径找
			$sc->checkFocusMsg($one);
			$focus=session('focus'.$one);dump($focus);
			if($one>0 && $focus==1){
				$uidarr[$i]='';//关注的uid删除
				//推送商品信息
				$ca_title="title_".$one;
				//$cache->$ca_title=$title;
				$ca_url="url_".$one;
				//$cache->$ca_url=$url;
				D("Wx/SendMsg")->focusmsg($one,$cache->$ca_title,$cache->$ca_url);
			}else{
			}//end if
		}//end foreach
		$uidarr=array_filter($uidarr);//数组去除空值
		dump($uidarr);
		$uidstr=implode(',',$uidarr);//dump($uidstr);//转换为字符串
		$cache->uidstr=$uidstr;
		
		session('focusmsg',0);  //"推送消息结束"
		$end_time=time();//执行完成时间
		if($end_time-$f_time>55){
			die;
		}else{
			sleeping:
			sleep(3); 
			goto againrun;
		}//end if
	}//end fun
}//end class